import React from "react";
import ReactDOM from "react-dom";
import { UpCircleFilled, DownCircleFilled } from "@ant-design/icons";
import "./index.css";

const MaxNum = 3;

function Asc(props) {
  const text = { fontSize: "20px", color: "#08c" };
  if (props.asc) {
    return <UpCircleFilled style={text} onClick={props.onClick} />;
  } else {
    return <DownCircleFilled style={text} onClick={props.onClick} />;
  }
}

function Square(props) {
  return (
    <button
      className={props.highlight ? "square-highlight" : "square"}
      onClick={props.onClick}
    >
      {props.value}
    </button>
  );
}

class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        value={this.props.squares[i]}
        highlight={this.props.highlights[i]}
        onClick={() => this.props.onClick(i)}
        key={i}
      />
    );
  }

  render() {
    let n = 0;
    let board = Array(MaxNum);
    for (let i = 0; i < MaxNum; i++) {
      let boardRow = Array(MaxNum).fill(null);
      for (let j = 0; j < MaxNum; j++, n++) {
        boardRow.push(this.renderSquare(n));
      }
      board.push(
        <div className="board-row" key={i}>
          {boardRow}
        </div>
      );
    }

    return <div>{board}</div>;
  }
}

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [{ squares: Array(MaxNum * MaxNum).fill(null) }],
      historySteps: Array(MaxNum * MaxNum).fill(null),
      stepNumber: 0,
      xIsNext: true,
      asc: true,
    };
  }

  render() {
    const history = this.state.history;
    const stepNumber = this.state.stepNumber;
    const current = history[this.state.stepNumber];
    const [winner, posHighlight] = calculateWinner(current.squares);

    const moves = history.map((step, move) => {
      const [posX, posY] = position(this.state.historySteps[move]);
      const desc = move
        ? "第 " + move + " 手 (" + posX + ", " + posY + ")"
        : "开始游戏";
      return (
        <li key={move}>
          <button
            onClick={() => this.jumpTo(move)}
            className={move === stepNumber ? "title-bold" : ""}
          >
            {desc}
          </button>
        </li>
      );
    });

    let status;
    if (winner === "平局") {
      status = "结果: " + winner;
    } else if (winner) {
      status = "胜: " + winner;
    } else {
      status = "落子: " + (this.state.xIsNext ? "X" : "O");
    }
    return (
      <div className="game">
        <div className="game-board">
          <Board
            squares={current.squares}
            highlights={posHighlight}
            onClick={(i) => this.handleClick(i)}
          />
        </div>
        <div className="game-info">
          <div className="title-bold">{status}</div>
          <Asc asc={this.state.asc} onClick={() => this.clickSort()} />
          <ol>{this.state.asc ? moves : moves.reverse()}</ol>
        </div>
      </div>
    );
  }

  clickSort() {
    this.setState({ asc: !this.state.asc });
  }

  handleClick(i) {
    const history = this.state.history.slice(0, this.state.stepNumber + 1);
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    const [winner] = calculateWinner(squares);
    if (winner || squares[i]) {
      return;
    }

    let historySteps = this.state.historySteps.slice(
      0,
      this.state.stepNumber + 1
    );
    historySteps.push(i);
    squares[i] = this.state.xIsNext ? "X" : "O";
    this.setState({
      history: history.concat([{ squares: squares }]),
      historySteps: historySteps,
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext,
    });
  }

  jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: step % 2 === 0,
    });
  }
}

// ========================================

ReactDOM.render(<Game />, document.getElementById("root"));

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2], // 连成行
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6], // 连成列
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8], // 对角线
    [2, 4, 6],
  ];
  let pos = Array(MaxNum * MaxNum).fill(false);
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      pos[a] = pos[b] = pos[c] = true;
      return [squares[a], pos];
    }
  }

  for (let i = 0; i < squares.length; i++) {
    if (squares[i] === null) {
      return [null, pos];
    }
  }
  return ["平局", pos];
}

function position(block) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
  ];

  for (let i = 0; i < lines.length; i++) {
    for (let j = 0; j < lines[i].length; j++) {
      if (lines[i][j] === block) {
        return [i + 1, j + 1];
      }
    }
  }

  return [null, null];
}
